/**
 * 
 */
package cc.rico.shiro.utils;

import org.apache.shiro.crypto.hash.DefaultHashService;
import org.apache.shiro.crypto.hash.Hash;
import org.apache.shiro.crypto.hash.HashRequest;
import org.apache.shiro.crypto.hash.HashService;
import org.apache.shiro.crypto.hash.Md5Hash;

/**
 * 加密工具
 * @author rico 2016年6月26日
 *
 */
public class CredentialsUtil {
	
	/**
	 * 密码加密 16进制
	 * @param algorithmName
	 * @param iterations
	 * @param salt
	 * @param source
	 * @return
	 */
	public static String encodeToHex(String algorithmName, int iterations, String salt, String source) {
		return getCredentialHash(algorithmName, iterations, salt, source).toHex();
	}
	
	/**
	 * 密码加密 base64
	 * @param algorithmName
	 * @param iterations
	 * @param salt
	 * @param source
	 * @return
	 */
	public static String encodeToBase64(String algorithmName, int iterations, String salt, String source) {
		return getCredentialHash(algorithmName, iterations, salt, source).toBase64();
	}
	
	/** 
	 * 
	 * @param algorithmName
	 * @param iterations
	 * @param salt
	 * @param source
	 * @return
	 */
	public static Hash getCredentialHash(String algorithmName, int iterations, String salt, String source) {
		HashRequest hashRequest = new HashRequest.Builder()
			.setAlgorithmName(Md5Hash.ALGORITHM_NAME)
			.setIterations(1)
			.setSalt(salt)
			.setSource(source)
			.build();
	
		HashService hashService = new DefaultHashService();
		Hash hash = hashService.computeHash(hashRequest);
		
		return hash;
	}
	
}
